package org.wukl.vhr.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wukl.vhr.mapper.MenuMapper;
import org.wukl.vhr.mapper.MenuRoleMapper;
import org.wukl.vhr.model.Hr;
import org.wukl.vhr.model.Menu;

import java.util.List;

@Service
public class MenuService {
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    MenuRoleMapper menuRoleMapper;
    public List<Menu> getMenuByHrId()
    {
        /**
         * 从SpringSecurity中获取当前登录用户，根据当前登录用户获取用户Id
         * SecurityContextHolder.getContext()
         * .getAuthentication().getPrincipal():从SpringSecurity中获取当前登录用户对象
         */

        return menuMapper.getMenuByHrId(((Hr) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal()).getId());
    }

    /**
     * 根据当前登录用户角色标识获取角色所有可访问菜单项
     * @return 角色菜单集合
     */
    public List<Menu> getMenuInfoByRole()
    {
       return menuMapper.getMenuInfoByRole();
    }

    /**
     * 加载所有树形菜单，用于角色分配访问权限
     * @return 所有树形菜单集合
     */
    public List<Menu> getAllMenus()
    {
        return menuMapper.getAllMenus();
    }

    /**
     *
     * @param rid:角色编号
     * @return 根据角色获取菜单编号集合信息
     */
    public List<Integer> getMenuIdsByRoleId(Integer rid)
    {
        return menuMapper.getMenuIdsByRoleId(rid);
    }

    /**
     * 根据角色编号更新角色访问权限信息
     * @param rid:角色编号
     * @param mids:选中权限菜单标识数组
     * @return 更新成功或失败
     */
    @Transactional
    public Boolean updateMenuByRoleId(Integer rid,Integer[] mids)
    {
            menuRoleMapper.deleteMenuRoleByRoleId(rid);
            Integer batchResult=menuRoleMapper.batchInsertMenuRole(rid,mids);
            return batchResult==mids.length;
    }
}
